
import pygame
import numpy as np
from scipy.io.wavfile import write

def test_play_sound():

    # 设置声音的基本参数
    sample_rate = 44100  # 标准的CD质量音频采样率
    duration = 1.0  # 每个音符持续的时间（秒）
    frequency = 440  # 初始音高，例如A4的频率是440Hz

    # 创建一个函数来生成单个音符的波形
    def generate_sine_wave(freq, duration, sample_rate):
        t = np.linspace(0, duration, int(sample_rate * duration), False)
        sine_wave = np.sin(freq * t * 2 * np.pi)
        return sine_wave

    # 创建一个函数来生成整个旋律
    def generate_melody(frequencies, durations):
        melody = []
        for freq, dur in zip(frequencies, durations):
            melody.append(generate_sine_wave(freq, dur, sample_rate))

        # 合并所有音符为一个数组
        melody = np.concatenate(melody)
        # 归一化以避免削波
        melody = melody * (32767 / np.max(np.abs(melody)))
        melody = melody.astype(np.int16)
        return melody

    # 初始化pygame
    pygame.mixer.init(sample_rate)

    # 定义旋律
    frequencies = [440, 554, 659, 698, 800]  # A4, C5, E5, F5
    durations = [1, 0.5, 0.5, 1, 1]  # 每个音符持续的时间

    melody = generate_melody(frequencies, durations)

    # 将旋律写入WAV文件
    write("melody.wav", sample_rate, melody)

    # 加载并播放旋律
    sound = pygame.mixer.Sound("melody.wav")
    sound.play()

    # 等待旋律播放完毕
    pygame.time.wait(int(sound.get_length() * 1000))

# 清理
pygame.quit()